<template>
  <!-- 搜索相关 start -->
  <el-form :model="queryParams" ref="refForm" size="default" :inline="true" v-show="showSearch" label-width="38px">
    <el-form-item label="文件名" prop="title" label-width="60px">
      <el-input v-model="queryParams.name" placeholder="请输入文件名" clearable @keyup.enter.native="handleGetList" />
    </el-form-item>
    <el-form-item label="创建日期" prop="startEndData" label-width="88px">
      <el-date-picker v-model="queryParams.startEndData" type="daterange" unlink-panels range-separator="到"
        start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" :size="size" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" icon="el-icon-search" size="default" @click="handleGetList">搜索</el-button>
      <el-button type="primary" icon="el-icon-refresh" size="default" @click="resetForm(refForm)">重置</el-button>
    </el-form-item>
  </el-form>
  <!-- 搜索相关 end -->

  <!-- 操作相关 start -->
  <el-row :gutter="10" class="mb8" v-if="fileListSinglePage">
    <el-col :span="1.5">
      <el-button type="primary" plain icon="el-icon-plus" size="default" @click="outerVisible = true" :disabled="true">新增</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="success" plain icon="el-icon-edit" size="default" @click="handleUpdate"
        :disabled="true">修改</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="danger" plain icon="el-icon-delete" size="default" @click="handleDeleteConfirmEvent"
        :disabled="true">删除</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="warning" plain icon="el-icon-download" size="default" :disabled="true">导出</el-button>
    </el-col>
    <el-col :span="1.5">
      <el-button type="info" plain icon="el-icon-s-operation" size="default" :disabled="true">日志</el-button>
    </el-col>
    <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="handleGetList"></right-toolbar> -->
  </el-row>
  <!-- 操作相关 end -->

  <!-- 表格相关 start -->
  <el-table :data="filterTableData" style="height: 550px;" ref="tableRef" @select="handleTableSelectChange"
    @select-all="handleTableSelectAllChange">
    <el-table-column type="selection" width="55" />
    <el-table-column label="序号" type="index" width="55" :index="indexMethod" />
    <el-table-column label="文件名" prop="name" width="150" />
    <el-table-column label="文件" prop="previewUrl" width="150">
      <template #default="scope">
        <el-image style="width: 100px; height: 100px; z-index: 2000;" :src="scope.row.previewUrl" :zoom-rate="1.2"
          :max-scale="7" :min-scale="0.2" :preview-src-list="scope.row.url" :initial-index="4" fit="cover"
          :preview-teleported="true" />
      </template>
    </el-table-column>
    <el-table-column label="文件大小" prop="size" width="110" show-overflow-tooltip>
      <template #default="scope">
        <span>{{ formatFileSize(scope.row.size) }}</span>
      </template>
    </el-table-column>
    <el-table-column label="创建时间" prop="createTime" width="200" />
    <el-table-column width="120">
      <template #header>
        <el-input v-model="search" size="small" placeholder="Type to search" />
      </template>
      <template #default="scope">
        <el-popconfirm width="220" confirm-button-text="确定" cancel-button-text="取消" :icon="InfoFilled"
          icon-color="#626AEF" title="确定要删除此照片么？" @confirm="handleDeleteConfirmEvent(scope.$index, scope.row)">
          <template #reference>
            <el-button type="primary" :icon="Delete" />
          </template>
        </el-popconfirm>
        <!-- </template> -->
      </template>
    </el-table-column>
  </el-table>
  <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
    :page-sizes="[10, 20, 50, 100, 200, 300, 400]" :small="small" :disabled="disabled" :background="background"
    layout="total, sizes, prev, pager, next, jumper" :total=pageData.totalNum @size-change="handleSizeChange"
    @current-change="handleCurrentChange" style="margin-top: 20px;" />
  <!-- 表格相关 end -->

  <el-form style="margin-top: 10px;" v-if="!fileListSinglePage">
    <el-button type="primary" icon="el-icon-search" size="default"
      @click="albumCollectionSettingSubmit">保存</el-button>
  </el-form>

</template>
<script lang="ts" setup>
import { computed, ref, reactive, onMounted } from 'vue'
import { showErrorMsg, showSuccessMsg, resetForm, indexMethod, formatDate } from '@/api/common';
import type { FormInstance } from 'element-plus'
import { ElTable, ElLoading } from 'element-plus'
import { Delete, InfoFilled } from '@element-plus/icons-vue'
import { formatFileSize } from '@/utils/fileSize';
import { filePage, fileDelete } from "@/api/file/file";
import { coverFileSetting, fileSetting } from "@/api/albumCollection/albumCollection";
import type { ApiResponse, PageData, PageResponse, OnlyIdRequest } from '@/api/common';
import type { FileData, QueryParams } from '@/api/file/file';
import type { AlbumCollectionRequest } from '@/api/albumCollection/albumCollection';
const size = ref<'default' | 'large' | 'small'>('default')
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
let outerVisible = ref(false)
// 显示搜索条件
let showSearch = ref<boolean>(true)
const refForm = ref<FormInstance>()
let onlyIdRequest = reactive<OnlyIdRequest>({
  id: null,
})
let pageData = reactive<PageData<FileData>>({
  totalNum: 0,
  tableData: [],
})
let queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  name: '',
  startEndData: '',
  startDate: '',
  endDate: '',
})
const search = ref('')
const filterTableData = computed(() =>
  pageData.tableData.filter(
    (data) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase()))
)
const props = withDefaults(defineProps<{
  // 相册合集id
  albumCollectionId: number,
  // 是否配置封面：是 封面；否 合集照片
  isCoverFile: boolean,
  // 是否是从左侧菜单进入
  fileListSinglePage: boolean,
  userId: number,
  selectedFileIdList: number[],
}>(), {
  fileListSinglePage: true,
})
// 已配置的角色设置勾选
const toggleSelection = (rows?: FileData[]) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      tableRef.value!.toggleRowSelection(row, undefined)
    })
  } else {
    tableRef.value!.clearSelection()
  }
}
// 监听 selectedIdList 的变化
// 这里拿到的pageData.tableData一直是空的，加的这个immediate: true ，watch 会在组件初始化时立即执行一次但是watch在onMounted前面执行了。
// 暂时改成延迟执行吧。
// 这里本质上只支持一个任务对应一个角色，所以传一个number就可以了，但是遇到一个问题：如果前后两次点击，两个人对应同一个角色，
// 那么子组件是无法监听到这个值的变化的，会出现理应勾选的角色，没有被勾选，即使前后两次点击，子组件经历了卸载到再加载。
// 那我完全可以在列表查询完后，再做勾选操作啊！就不需要watch了。
// watch(() => props.selectedFileIdList, (newVal) => {

//   // todo 这里有个隐患，因为获取pageData.tableData有网络延迟，如果长于50ms，那么可能会勾选失败。
//   setTimeout(() => {
//     let selectedFileIdList = pageData.tableData.filter(data => newVal.includes(data.id));
//     // 设置被选中的文件
//     toggleSelection(selectedFileIdList);
//   }, 300);
// });
// }, { immediate: true });
const tableRef = ref<InstanceType<typeof ElTable>>()
let albumCollectionRequest = reactive<AlbumCollectionRequest>({
  id: null,
  coverFileId: 0,
  fileIdList: [],
})
const albumCollectionSettingSubmit = () => {
  if (props.isCoverFile) {
    if (props.selectedFileIdList.length > 1) {
      showErrorMsg("封面只能选一张！")
      return;
    }
    if (props.selectedFileIdList.length == 0) {
      showErrorMsg("请选择一张作为封面！")
      return;
    }
    albumCollectionRequest.coverFileId = props.selectedFileIdList[0];
  } else {
    if (props.selectedFileIdList.length == 0) {
      showErrorMsg("请至少选择一张！")
      return;
    }
    albumCollectionRequest.fileIdList = props.selectedFileIdList;
  }
  albumCollectionRequest.id = props.albumCollectionId;
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  if (props.isCoverFile) {
    coverFileSetting(albumCollectionRequest).then((res: ApiResponse<string>) => {
      loading.close()
      if (res.status != 200) {
        showErrorMsg(res.msg);
      } else {
        showSuccessMsg("配置成功");
      }
    })
  } else {
    fileSetting(albumCollectionRequest).then((res: ApiResponse<string>) => {
      loading.close()
      if (res.status != 200) {
        showErrorMsg(res.msg);
      } else {
        showSuccessMsg("配置成功");
      }
    })
  }

}
const handleDeleteConfirmEvent = (index: number, row: FileData) => {
  onlyIdRequest.id = row.id;
  fileDelete(onlyIdRequest).then((res: ApiResponse<string>) => {
    // console.log(res);
    if (res.status != 200) {
      showErrorMsg(res.msg);
    } else {
      showSuccessMsg("删除成功")
      handleGetList();
    }
  });
  // console.log(index, row.id)
}
const handleSizeChange = (newSize: number) => {
  // console.log(`${newSize} items per page`)
  queryParams.pageSize = newSize;
  handleGetList();
}
// 列表数据延迟勾选
const rowSelectTimeout = () => {
  setTimeout(() => {
    let selectedRoleList = pageData.tableData.filter(data => props.selectedFileIdList.includes(data.id));
    // 设置被选中的文件
    toggleSelection(selectedRoleList);
  }, 50)
}
const handleCurrentChange = (newPage: number) => {
  queryParams.pageNum = newPage;
  handleGetList();
}
const handleTableSelectChange = (selection: FileData[], row: FileData) => {
  if (props.selectedFileIdList.includes(row.id)) {
    const index = props.selectedFileIdList.indexOf(row.id);
    if (index !== -1) {
      props.selectedFileIdList.splice(index, 1);
    }
  } else {
    props.selectedFileIdList.push(row.id)
  }
}
const handleTableSelectAllChange = (selection: FileData[]) => {
  for (const item of selection) {
    if (!props.selectedFileIdList.includes(item.id)) {
      props.selectedFileIdList.push(item.id)
    }
  }
}
const handleUpdate = (row: FileData) => {}
const handleGetList = () => {
  const startEndDate = queryParams.startEndData
  if (startEndDate && startEndDate.length === 2) {
    queryParams.startDate = formatDate(startEndDate[0]);
    queryParams.endDate = formatDate(startEndDate[1]);
  } else {
    queryParams.startDate = '';
    queryParams.endDate = '';
  }
  filePage(queryParams).then((res: ApiResponse<PageResponse<FileData>>) => {
    if (res.status != 200) {
      showErrorMsg(res.msg);
      return;
    }
    let totalTemp = parseInt(res.data.total);
    pageData.totalNum = totalTemp;
    pageData.tableData = res.data.records;
    // 勾选
    if (!props.fileListSinglePage) {
      rowSelectTimeout();
    }
  });
}
onMounted(() => {
  handleGetList();
})
const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
];
</script>
<style></style>